// 格式化时间
function formatTime(date) {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
}

// 更新状态指示器
function updateStatusIndicators(temperature, humidity, light) {
  const tempStatus = document.getElementById('temp-status');
  if (tempStatus) {
    tempStatus.textContent = temperature < 18 ? '偏低' :
      temperature < 25 ? '正常' :
        temperature < 30 ? '偏高' : '过高';
    tempStatus.className = temperature < 18 ? 'text-blue-600' :
      temperature < 25 ? 'text-green-600' :
        temperature < 30 ? 'text-yellow-600' : 'text-red-600';
  }

  const humidityStatus = document.getElementById('humidity-status');
  if (humidityStatus) {
    humidityStatus.textContent = humidity < 40 ? '干燥' :
      humidity < 60 ? '正常' : '潮湿';
    humidityStatus.className = humidity < 40 ? 'text-orange-600' :
      humidity < 60 ? 'text-green-600' : 'text-blue-600';
  }

  const lightStatus = document.getElementById('light-sensor-status');
  if (lightStatus) {
    lightStatus.textContent = light < 500 ? '偏暗' :
      light < 3000 ? '适中' : '过亮';
    lightStatus.className = light < 500 ? 'text-purple-600' :
      light < 3000 ? 'text-green-600' : 'text-yellow-600';
  }
}

// 更新设备状态
function updateDeviceStatus(door, window, light) {
  const doorStatus = document.getElementById('door-status');
  const windowStatus = document.getElementById('window-status');
  const lightStatus = document.getElementById('device-light-status');

  if (doorStatus) {
    const doorIndicator = doorStatus.querySelector('.device-indicator');
    const doorText = doorStatus.querySelector('span:not(.device-indicator)');
    doorText.textContent = door;
    doorIndicator.className = `device-indicator ${door === 'open' ? 'bg-device_on' : 'bg-device_off'}`;
  }

  if (windowStatus) {
    const windowIndicator = windowStatus.querySelector('.device-indicator');
    const windowText = windowStatus.querySelector('span:not(.device-indicator)');
    windowText.textContent = window;
    windowIndicator.className = `device-indicator ${window === 'open' ? 'bg-device_on' : 'bg-device_off'}`;
  }

  if (lightStatus) {
    const lightIndicator = lightStatus.querySelector('.device-indicator');
    const lightText = lightStatus.querySelector('span:not(.device-indicator)');
    lightText.textContent = light;
    lightIndicator.className = `device-indicator ${light === 'on' ? 'bg-device_on' : 'bg-device_off'}`;
  }
}

// 更新环境数据
function updateEnvironmentData(data) {
  if (!data || !['Temperature', 'Humidity', 'Brightness', 'door', 'window', 'light', 'I', 'U', 'W'].every(key => data.hasOwnProperty(key))) {
    console.error('无效数据格式:', data);
    return;
  }

  const now = new Date();
  const tempElement = document.getElementById('temperature');
  const humidityElement = document.getElementById('humidity');
  const lightElement = document.getElementById('light');
  const currentElement = document.getElementById('current');
  const voltageElement = document.getElementById('voltage');
  const powerElement = document.getElementById('power');

  tempElement.textContent = `${parseFloat(data.Temperature).toFixed(1)}°C`;
  humidityElement.textContent = `${parseFloat(data.Humidity).toFixed(1)}%`;
  lightElement.textContent = `${parseFloat(data.Brightness).toFixed(0)} lux`;
  currentElement.textContent = `${parseFloat(data.I).toFixed(1)} A`;
  voltageElement.textContent = `${parseFloat(data.U).toFixed(1)} V`;
  powerElement.textContent = `${parseFloat(data.W).toFixed(1)} W`;
  document.getElementById('lastUpdate').textContent = formatTime(now);

  [tempElement, humidityElement, lightElement, currentElement, voltageElement, powerElement].forEach(el => {
    el.classList.remove('data-update-animation');
    void el.offsetWidth;
    el.classList.add('data-update-animation');
  });

  updateStatusIndicators(data.Temperature, data.Humidity, data.Brightness);
  updateDeviceStatus(data.door, data.window, data.light);
  resetRefreshButton();
}

// 发送刷新请求
function sendRefreshRequest() {
  const refreshButton = document.getElementById('refreshButton');
  refreshButton.disabled = true;
  refreshButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 刷新中...';

  fetch('/api/control', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ device: 'env', action: 'get' })
  })
    .then(res => res.json())
    .then(data => {
      if (data.status !== 'success') throw new Error(data.message || '刷新失败');
    })
    .catch(err => {
      console.error('刷新请求失败:', err);
      showNotification('刷新失败', err.message, 'error');
    })
    .finally(() => setTimeout(resetRefreshButton, 5000));
}

// 重置刷新按钮
function resetRefreshButton() {
  const refreshButton = document.getElementById('refreshButton');
  refreshButton.disabled = false;
  refreshButton.innerHTML = '<i class="fa fa-refresh mr-2"></i> 刷新环境数据';
}

// 显示通知
function showNotification(title, message, type = 'info') {
  console.log(`[${type.toUpperCase()}] ${title}: ${message}`);
  // 实际项目中可替换为 Toast 或 Modal
}

// 页面加载后初始化
document.addEventListener('DOMContentLoaded', () => {
  const socket = io({
    reconnection: true,
    reconnectionAttempts: 5,
    reconnectionDelay: 1000,
    timeout: 10000
  });

  const connectionStatus = document.getElementById('connectionStatus');
  const realtimeStatus = document.getElementById('realtimeStatus');
  const serverStatus = document.getElementById('serverStatus');

  const updateConnectionStatus = (isConnected, reason = '连接成功') => {
    connectionStatus.className = `connection-status ${isConnected ? 'bg-green-500' : 'bg-red-500'}`;
    connectionStatus.innerHTML = `<i class="fa fa-wifi mr-2"></i> <span>${isConnected ? '连接已建立' : `连接断开 (${reason})`}</span>`;
    realtimeStatus.textContent = isConnected ? '已连接' : '断开';
    serverStatus.textContent = isConnected ? '在线' : '离线';
    serverStatus.className = isConnected ? 'text-green-500' : 'text-red-500';
  };

  updateConnectionStatus(false, '等待连接');

  socket.on('connect', () => updateConnectionStatus(true));
  socket.on('disconnect', reason => updateConnectionStatus(false, reason));
  socket.on('connect_error', err => updateConnectionStatus(false, `错误: ${err.message}`));
  socket.on('data_update', updateEnvironmentData);

  document.getElementById('refreshButton').addEventListener('click', sendRefreshRequest);
});